package com.example.ivideo_2211a.widget

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import androidx.core.animation.doOnEnd

/**
 * 自定义圆形倒计时跳过控件
 * 显示一个圆形进度条和倒计时数字，用于启动页的跳过功能
 */
class SkipCircleView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
    // 圆环画笔
    private val circlePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        strokeWidth = 12f
        color = Color.parseColor("#FF9800")
    }
    // 文字画笔
    private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.BLACK
        textSize = 48f
        textAlign = Paint.Align.CENTER
    }
    // 扫描角度（用于绘制圆弧）
    private var sweepAngle = 360f
    // 倒计时秒数
    private var seconds = 3
    // 属性动画器
    private var animator: ValueAnimator? = null
    // 倒计时结束回调
    var onSkip: (() -> Unit)? = null

    /**
     * 开始倒计时动画
     * @param duration 动画持续时间（毫秒）
     * @param seconds 倒计时秒数
     */
    fun start(duration: Long = 3000, seconds: Int = 3) {
        this.seconds = seconds
        sweepAngle = 360f
        animator?.cancel()
        animator = ValueAnimator.ofFloat(360f, 0f).apply {
            this.duration = duration
            addUpdateListener {
                sweepAngle = it.animatedValue as Float
                invalidate()
            }
            doOnEnd {
                onSkip?.invoke()
            }
            start()
        }
    }

    /**
     * 绘制控件内容
     * @param canvas 画布
     */
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val radius = (width.coerceAtMost(height) - 24) / 2f
        val cx = width / 2f
        val cy = height / 2f
        // 绘制圆弧进度条
        canvas.drawArc(
            cx - radius, cy - radius, cx + radius, cy + radius,
            -90f, sweepAngle, false, circlePaint
        )
        // 计算并绘制倒计时数字
        val remain = (sweepAngle / 360f * seconds).toInt() + 1
        val text = "$remain"
        val textY = cy - (textPaint.descent() + textPaint.ascent()) / 2
        canvas.drawText(text, cx, textY, textPaint)
    }
}

